package com.ruibang.glass.produce.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 文件持久化操作
 */

@Slf4j
public class FileUtil {

    public static String file2disk(MultipartFile file, String dir, String fileId,String disturbCode,String fileName) {
        try {
            File fileDir = createDirIfNoneExists(dir + File.separator + fileId+File.separator+disturbCode);
            File saveFile = new File(fileDir,fileName);
            file.transferTo(saveFile);
            if(saveFile.exists() && saveFile.length() == file.getSize()){
                return saveFile.getAbsolutePath();
            }
            else{
                saveFile.delete();
                log.error("文件上传字节与文件大小不一致");
                throw new RuntimeException("文件上传异常中断，请重试");
            }
        } catch (Exception e) {
            log.error("文件上传失败:");
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
    }

    public static String image2disk(MultipartFile file, String dir, String appendId) {
        try {
            File fileDir = createDirIfNoneExists(dir + File.separator + appendId);
            File saveFile = new File(fileDir,file.getOriginalFilename());
            file.transferTo(saveFile);
            if(saveFile.exists() && saveFile.length() == file.getSize()){
                return saveFile.getAbsolutePath();
            }
            else{
                saveFile.delete();
                log.error("文件上传字节与文件大小不一致");
                throw new RuntimeException("文件上传异常中断，请重试");
            }
        } catch (Exception e) {
            log.error("文件上传失败:");
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
    }

    /**
     *
     * @param zipFilePath zip压缩文件路径
     * @return sql路径
     */
    public String unzipFile(String zipFilePath,String targetDir){
        long startTime=System.currentTimeMillis();
        try {
            ZipInputStream Zin=new ZipInputStream(new FileInputStream(
                    zipFilePath));//输入源zip路径
            BufferedInputStream Bin=new BufferedInputStream(Zin);
            File Fout=null;
            ZipEntry entry;
            String sqlfileName = null;
            try {
                while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){
                    log.error("zip"+ targetDir + entry.getName());
                    Fout=new File(targetDir,entry.getName());
                    if(!Fout.exists()){
                        (new File(Fout.getParent())).mkdirs();
                    }
                    FileOutputStream out=new FileOutputStream(Fout);
                    BufferedOutputStream Bout=new BufferedOutputStream(out);
                    int b;
                    while((b=Bin.read())!=-1){
                        Bout.write(b);
                    }
                    Bout.close();
                    out.close();
                    log.info("文件解压成功，源目录：" + zipFilePath + ",目标目录：" + targetDir);
                }
                Bin.close();
                Zin.close();
            } catch (IOException e) {
                log.error("文件解压失败:");
                e.printStackTrace();
                throw new RuntimeException("文件解压失败");
            }
        } catch (FileNotFoundException e) {
            log.error("文件解压失败:");
            e.printStackTrace();
            throw new RuntimeException("文件解压失败");
        }
        long endTime=System.currentTimeMillis();
        System.out.println("耗费时间： "+(endTime-startTime)+" ms");
        return "sss";
    }

    public boolean fileDel(String workId, String studentNumber) {
        File saveFile = new File("dir" + File.separator + workId + File.separator + studentNumber);
        return saveFile.delete();
    }

    public Optional<File> getFile(String workId, String studentNumber) {
        File saveFile = new File("dir" + File.separator + workId + File.separator + studentNumber);
        if (!saveFile.exists()) {
            return Optional.empty();
        }
        if (!saveFile.canRead()) {
            return Optional.empty();
        }
        return Optional.of(saveFile);
    }

    public List<File> getFiles(String workId) {
        File workDir = new File("dir" + File.separator + workId);
        File[] files = workDir.listFiles();
        if (files != null) {
            return Arrays.asList(files);
        } else {
            return Collections.emptyList();
        }
    }

    private static File createDirIfNoneExists(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            boolean mkdir = file.mkdirs();
            if (!mkdir) {
                log.error("create dir failure and dir path: {}", dirPath);
                throw new RuntimeException("创建文件夹失败");
            }
            return file;
        }
        return file;
    }

    /**
      * @功能 下载临时素材接口
      * @param filePath 文件将要保存的目录
      * @param method 请求方法，包括POST和GET
      * @param url 请求的路径
      * @return
      */

    /**
     * @功能 下载临时素材接口
     * @param filePath 文件将要保存的目录
     * @param method 请求方法，包括POST和GET
     * @param url 请求的路径
     * @return
     */

    public static File saveUrlAs(String url,String filePath,String method){
        //System.out.println("fileName---->"+filePath);
        //创建不同的文件夹目录
        File file=new File(filePath);
        //判断文件夹是否存在
        if (!file.exists())
        {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type","text/html; charset=utf-8");
            conn.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
            // 建立实际的连接
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {

                filePath += "/";
            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）

            fileOut = new FileOutputStream(filePath+UUID.randomUUID().toString().replace("-","").concat(".html"));
            bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
        }
        catch (Exception e){
            log.error("读取文件异常:"+e.getMessage());
        }finally {
            try {
                bos.close();
                bis.close();
                fileOut.close();
                inputStream.close();
            } catch (IOException e) {
                log.error("关闭流接口异常:"+e.getMessage());
            }
            conn.disconnect();
        }

        return file;
    }



    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            System.out.println("读取响应：" + urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type","text/html; charset=utf-8");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String StringFilter(String str) throws PatternSyntaxException{
        // 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").replaceAll("\\s*", "");
    }





    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ( (hasRead = fis.read(bbuf)) > 0 ) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }




    public static void main(String[] args) {
       String aa = " 中  国国际.DOCX%RT$E33 88999  ";
        System.out.println(StringFilter(aa));
    }







}
